<template>
  <section>
    <h4 class="divider">基础信息</h4>
    <div class="jar-update">
      <el-form :model="formInline">
        <ul>
          <li>
            <el-form-item label="类名称" :rules="[{ required: true }]">
              <el-input
                type="text"
                v-model="formInline.classFullName"
              ></el-input>
            </el-form-item>
          </li>
          <li>
            <el-form-item label="jar文件包" :rules="[{ required: true }]">
              <div>
                <input
                  type="file"
                  name="file"
                  id="file"
                  @change="uploadFun"
                  class="inputfile"
                />
                <label for="file">选择文件</label>
                <p>{{ formInline.jarFile }}</p>
              </div>

              <!-- <el-upload
                ref="upload"
                class="upload-button"
                style="width: 100%"
                :headers="config.headers"
                action="server-proxy/svc/version/jar/upload"
                :on-exceed="handleExceed"
                :limit="1"
                :on-success="handleSuccess"
              >
                <el-button type="primary">点击上传</el-button>
              </el-upload>
              <el-input
                type="text"
                v-model="formInline.jarFile"
                v-show="false"
              ></el-input> -->
            </el-form-item>
          </li>
        </ul>
      </el-form>
    </div>
    <el-divider></el-divider>
    <div>
      <el-button type="text" @click="handleDownloadSDK"
        >开发SDK包下载</el-button
      >
    </div>
  </section>
</template>

<script>
import { reactive, ref, onMounted, defineComponent, watch } from "vue";
import { useStore } from "vuex";
import { useRoute } from "vue-router";
import { downloadSDK, uploadSDK, uploadPatch } from "@/api/service.js";
import { getToken, getCurrentOrg } from "@/utils/auth";
import { fetchDownload } from "@/utils/index.js";
import calcMD5 from "@/utils/md5.js";
import { ElMessage } from "element-plus";
export default defineComponent({
  components: {},
  setup() {
    const route = useRoute();
    const store = useStore();
    const upload = ref();
    const formInline = ref({ classFullName: "", jarFile: "" });
    const config = reactive({ headers: {} });
    config.headers["Authorization"] = getToken();
    config.headers["ORG"] = getCurrentOrg();
    const uploadFun = async () => {
      var bytesPerPiece = 1024 * 1024 * 5; // 每个文件切片大小定为1MB .
      var totalPieces;
      var blob = document.getElementById("file").files[0];
      var start = 0;
      var end;
      var index = 0;
      var filesize = blob.size;
      var filename = blob.name;
      var random = Math.random();
      console.log(index, random);
      //计算文件切片总数
      totalPieces = Math.ceil(filesize / bytesPerPiece);
      while (start < filesize) {
        end = start + bytesPerPiece;
        if (end > filesize) {
          end = filesize;
        }
        var chunk = blob.slice(start, end); //切割文件
        var sliceIndex = blob.name + index;
        var formData = new FormData();
        var uploadName = calcMD5(random + filename);
        formData.append("file", chunk, uploadName);
        console.log(formData, chunk, uploadName, index);
        let res = await uploadPatch(formData, {
          md5: uploadName,
          index: index + 1,
          total: totalPieces,
        });
        if (res.message == "请求成功") {
          ElMessage.success(`文件分片${index + 1}，上传成功`);
          formInline.value.jarFile = res.data;
        }
        start = end;
        index++;
      }
    };

    const handleSuccess = (res, file, fileList) => {
      formInline.value.jarFile = res.data;
      console.log(formInline.value.jarFile);
    };
    const handleExceed = async (files) => {
      upload.value.clearFiles();
      upload.value.handleStart(files[0]);
      var formdata = new FormData();
      formdata.append("file", files[0]);
      let res = await uploadSDK(formdata);
      handleSuccess(res);
    };
    const handleDownloadSDK = async () => {
      let res = await downloadSDK();
      fetchDownload(res);
    };
    watch(
      () => formInline.value,
      (newData, oldData) => {
        // console.log(newData);
        store.commit("app/PUT_SERVICE_JAR", newData);
        // console.log("state：", store.state.app.serviceBody);
        // ctx.emit("callRequest", requestData.value);
      },
      { deep: true }
    );
    let editMode = route.name == "EditService";
    onMounted(() => {
      if (editMode) {
        formInline.value =
          store.state.app.serviceBody.ifParam.adptIfCfgJar || {};
      }
    });
    return {
      handleExceed,
      handleSuccess,
      downloadSDK,
      formInline,
      upload,
      config,
      handleDownloadSDK,
      uploadFun,
    };
  },
});
</script>

<style lang="scss" scoped>
.jar-update {
  overflow: hidden;
}

.inputfile {
  width: 0.1px;
  height: 0.1px;
  opacity: 0;
  overflow: hidden;
  position: absolute;
  z-index: -1;
}
.inputfile + label {
  font-size: 14px;
  color: white;
  display: inline-block;
  background-color: #2e69eb;
  border-color: #2e69eb;
  border-radius: 18px;
  padding: 0 20px;
}
.inputfile:focus + label,
.inputfile + label:hover {
  background-color: rgb(88, 135, 239);
  cursor: pointer;
}
</style>
